package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.GroupSetmealMapper;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.CheckItemVO;
import com.itheima.pojo.CheckPageQueryDTO;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private GroupSetmealMapper groupSetmealMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 修改套餐
     * @param setmeal
     * @param checkgroupIds
     */
    @Transactional
    public void updateById(Setmeal setmeal, List<Integer> checkgroupIds) {
        setmealMapper.update(setmeal);
        Integer setmealId = setmeal.getId();
        groupSetmealMapper.deleteBySetmeal(setmealId);
        for (Integer checkgroupId : checkgroupIds) {
            groupSetmealMapper.insert(setmealId,checkgroupId);
        }

    }

    /**
     * 新增套餐
     * @param setmeal
     * @param checkgroupIds
     */
    @Transactional
    public void add(Setmeal setmeal, List<Integer> checkgroupIds) {
        setmealMapper.insert(setmeal);
        //向redis中保存数据
        String key = "newPicture";
        SetOperations redis = redisTemplate.opsForSet();
        redis.add(key,setmeal.getImg());

        Integer id = setmeal.getId();
        for (Integer groupId : checkgroupIds) {
            groupSetmealMapper.insert(id,groupId);
        }
    }

    /**
     * 根据主键ID进行套餐查询
     * @param id
     * @return
     */
    public Setmeal geyById(Long id) {
        Setmeal setmeal = setmealMapper.getById(id);
        return setmeal;
    }

    /**
     * 套餐分页查询
     * @param queryPageBean
     * @return
     */
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Setmeal> page = setmealMapper.pageQuery(queryPageBean);
        return new PageResult(page.getTotal(),page.getResult());
    }
}
